//
//  XS_FenleiVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/9.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class XS_FenleiVC: XS_BaseVC {
    
    private lazy var page = 0
    private lazy var dataPS = PublishSubject<[XS_menuItemCurriculumDtoListM]>()
    private lazy var data: [XS_menuItemCurriculumDtoListM] = []
    private lazy var footer = MJRefreshBackNormalFooter()

    lazy var tableLeft = UITableView(frame: .zero, style: .grouped)
    lazy var table = UITableView(frame: .zero, style: .grouped)
    var selectModel: XS_HomeTopM?
    
    override func upView() {
//        title = "分类"
        title = "课程分类"
        
        let item = UIBarButtonItem(image: UIImage(named: "icon_搜索"), style: .done, target: nil, action: nil)
        navigationItem.rightBarButtonItem = item
        item.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                let vc = XS_SearchVC()
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        
        table.showsVerticalScrollIndicator = false
//        table.bounces = false
        table.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        table.separatorStyle = .none
        table.rowHeight = .scale*104
        table.sectionHeaderHeight = 0
        table.sectionFooterHeight = 0
        table.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.register(XS_FenleiCell.self, forCellReuseIdentifier: "cell")
        table.register(XS_FenleiCell.self, forCellReuseIdentifier: "offline")
        view.addSubview(table)
        table.snp.makeConstraints({
            $0.top.bottom.equalToSuperview()
            $0.left.equalTo(.scale*100)
            $0.right.equalToSuperview().offset(.scale*4)
        })
        
        let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, XS_menuItemCurriculumDtoListM>>(configureCell: { ds, tv, ip, it in
            let identifier =  it.curriculumForm == "offline" ? "offline" : "cell"
            let cell = tv.dequeueReusableCell(withIdentifier: identifier, for: ip) as! XS_FenleiCell
            cell.modelPS.onNext(it)
            return cell
        })
        table.rx.modelSelected(XS_menuItemCurriculumDtoListM.self)
            .asDriver()
            .drive(onNext: { item in
                let vc = item.curriculumForm == "online" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = "\(item.id)"
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        dataPS.asDriver(onErrorJustReturn: [])
            .flatMapLatest { Driver.just([SectionModel<String, XS_menuItemCurriculumDtoListM>(model: "", items: $0)]) }
            .drive(table.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        table.mj_footer = footer
        footer.rx.refresh
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.loadMore()
            }).disposed(by: disposeBag)
        table.mj_footer?.ignoredScrollViewContentInsetBottom = (UIApplication.shared.statusBarFrame.size.height == 44) ? 34 : 0
        
        
        tableLeft.showsVerticalScrollIndicator = false
        tableLeft.bounces = false
        tableLeft.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        tableLeft.separatorStyle = .none
        tableLeft.rowHeight = .scale*48
        tableLeft.sectionHeaderHeight = 0
        tableLeft.sectionFooterHeight = 0
        tableLeft.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        tableLeft.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        tableLeft.register(XS_FenleiLeftCell.self, forCellReuseIdentifier: "cell")
        view.addSubview(tableLeft)
        tableLeft.snp.makeConstraints({
            $0.top.bottom.left.equalToSuperview()
            $0.width.equalTo(.scale*104)
        })
        
        tableLeft.rx.modelSelected(XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] item in
                self?.page = 0
                self?.selectModel = item
                self?.loadMore()
            }).disposed(by: disposeBag)
        let ds = RxTableViewSectionedReloadDataSource<SectionModel<String, XS_HomeTopM>>(configureCell: { [weak self] ds, tv, ip, it in
            let cell = tv.dequeueReusableCell(withIdentifier: "cell", for: ip) as! XS_FenleiLeftCell
//            cell.label.text = XS_Singleton.shared.infoModel == nil ? it.name : it.industryName
            cell.label.text = it.industryName
            if it.id == self?.selectModel?.id {
                tv.selectRow(at: ip, animated: true, scrollPosition: .none)
            }
            return cell
        })
        
        // 游客模式跟登录模式，进入课程分类调同一个接口。排序保持一致。
//        let allIndustryApi = XS_Singleton.shared.infoModel == nil ? "/industry/queryAllIndustryApi" : "/industry/queryAllStatusApi"
//        let allIndustryApi = "/industry/queryAllIndustryApi"
//        XS_NetWork.requestJson(allIndustryApi)
        XS_NetWork.requestJson("/industry/queryAllIndustryBySearchType", parameters: ["searchType" : "curriculum"])
            .mapModels(type: XS_HomeTopM.self)
            .map({ $0.0 })
            .asDriver(onErrorJustReturn: [])
            .flatMapLatest({ [weak self] models in
                self?.page = 0
                self?.selectModel = models.first
                self?.loadMore()
                return Driver.just([SectionModel<String, XS_HomeTopM>(model: "", items: models)])
            }).drive(tableLeft.rx.items(dataSource: ds))
            .disposed(by: disposeBag)
        
        
//        Driver.just([SectionModel<String, String>(model: "", items: ["推荐","智能财税","母婴护理","老年看护","物流管理","财务数据分析","管理会计应用","管理会计应用","数据分析","数据分析","数据分析","数据分析"])])
//            .drive(tableLeft.rx.items(dataSource: ds))
//            .disposed(by: disposeBag)
//        tableLeft.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .none)
        
        
    }
    
    func loadMore() {
        guard let model = selectModel else { return }
        if page == 0 {
            data.removeAll()
        }
        let param: [String:Any] = [
            "pageNo":page+1,
//            "curriculumName": model.industryName,
            "industryId": model.id
        ]
        
        XS_NetWork.requestJson("/curriculum/queryCurriculum", parameters: param)
            .mapModel(type: XS_queryVipCurriculumM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.page = model.current
                self.data += model.records
                self.dataPS.onNext(self.data)
                if model.current < model.pages {
                    self.footer.endRefreshing()
                } else {
                    self.footer.endRefreshingWithNoMoreData()
                }
            }).disposed(by: disposeBag)
    }

}

class XS_FenleiLeftCell: XS_BaseTCell {
    lazy var label = UILabel.xsLabel(size: .scale*13, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1))
    lazy var tip = UIView()
    override func upView() {
        selectionStyle = .none // 去掉点击样式
        backgroundColor = .clear
        contentView.clipsToBounds = true
        contentView.addSubview(label)
        label.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*12)
            $0.right.lessThanOrEqualToSuperview()
        })
        tip.isHidden = true
        tip.layer.cornerRadius = .scale*4
        tip.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        contentView.addSubview(tip)
        tip.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.width.equalTo(.scale*8)
            $0.height.equalTo(.scale*24)
            $0.centerX.equalTo(contentView.snp.left)
        })
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        tip.isHidden = !selected
        label.textColor = selected ? #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1) : #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1)
        backgroundColor = selected ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) : .clear
    }
}

class XS_FenleiCell: XS_BaseTCell {
    lazy var modelPS = PublishSubject<XS_menuItemCurriculumDtoListM>()
    
    public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        upView(reuseIdentifier)
    }
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func getLineEdgeInsets() -> UIEdgeInsets {
        UIEdgeInsets(top: 0, left: .scale*16, bottom: 0, right: -.scale*16)
    }
    func upView(_ reuseIdentifier: String?) {
        super.upView()
        
        let view = reuseIdentifier == "offline" ? getXianxia() : getXianShang()
        contentView.addSubview(view)
        view.snp.makeConstraints({
            $0.edges.equalTo(UIEdgeInsets(top: .scale*16, left: .scale*16, bottom: 0, right: .scale*16))
        })
    }
    
    func getXianxia() -> UIView {
        let view = UIView()
        
        let imgV = UIImageView()
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*100, height: .scale*72)
        view.addSubview(imgV)
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        
        let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
        imgV.addSubview(tagsView)
        let sLayer = CAShapeLayer()
        sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
        tagsView.layer.addSublayer(sLayer)
        let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
        tagsView.addSubview(tagLabel)
        tagLabel.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        
        let layerView = UIView()
        layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
        layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
        layerView.alpha = 1
        // fillCode
        let bglayer1 = CAGradientLayer()
        bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
        bglayer1.locations = [0, 1]
        bglayer1.frame = layerView.bounds
        layerView.layer.addSublayer(bglayer1)
        bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
        bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
        imgV.addSubview(layerView)
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "线下课")
        layerView.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1))
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalToSuperview()
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let icon = UIImageView(image: UIImage(named: "icon_12px_定位"))
        icon.frame = CGRect(x: .scale*112, y: .scale*28, width: .scale*12, height: .scale*12)
        view.addSubview(icon)
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1))
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.centerY.equalTo(icon.snp.centerY)
            $0.left.equalTo(icon.snp.right).offset(.scale*4)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .medium, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1))
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(-.scale*16)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.width.lessThanOrEqualTo(.scale*150)
        }
        let fm = DateFormatter()
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let label4 = UILabel()
        
        view.addSubview(label4)
        label4.snp.makeConstraints({
//            $0.right.equalToSuperview()
            $0.left.equalTo(label3.snp.right).offset(0)
            $0.bottom.equalTo(-.scale*16)
        })
        
//        let line = UIView()
//        line.backgroundColor = #colorLiteral(red: 0.9019607843, green: 0.9137254902, blue: 0.9450980392, alpha: 1)
//        view.addSubview(line)
//        line.snp.makeConstraints({
//            $0.left.bottom.right.equalToSuperview()
//            $0.height.equalTo(1)
//        })
        
        modelPS.subscribe(onNext: { item in
            imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
//            let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
            let text = NSMutableAttributedString()
            if item.isFree == "userPay" {
                let attr = NSMutableAttributedString(string: " | ￥")
                attr.yy_font = .xsFont(name: .medium, .scale*12)
                text.append(attr)
            }
            do {
                let attr = NSMutableAttributedString(string: item.isFree == "userPay" ? item.price : " | 免费")
                attr.yy_font = .xsFont(name: .medium, .scale*12)
                text.append(attr)
            }
            text.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
            text.yy_alignment = .right
            label4.attributedText = text
            if let date = fm.date(from: item.startTime) {
                let fm1 = DateFormatter()
//                fm1.dateFormat = "d.M EE"
                fm1.dateFormat = "MM-dd"
                label3.text = fm1.string(from: date)
            }
            label2.text = item.offlineAddress
            label1.text = item.curriculumName
            tagsView.isHidden = true
            layerView.isHidden = false
//            if item.isFree == "userFree" {
//                tagsView.isHidden = false
//            } else if item.vipIsFree == "vipFree" {
//                layerView.isHidden = false
//            }
        }).disposed(by: disposeBag)
        
        return view
    }
    
    func getXianShang() -> UIView {
        let view = UIView()
        
        let imgV = UIImageView()
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*100, height: .scale*72)
        view.addSubview(imgV)
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        
        let layerView = UIView()
        layerView.isHidden = true
        layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
        layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
        layerView.alpha = 1
        // fillCode
        let bglayer1 = CAGradientLayer()
        bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
        bglayer1.locations = [0, 1]
        bglayer1.frame = layerView.bounds
        layerView.layer.addSublayer(bglayer1)
        bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
        bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
        imgV.addSubview(layerView)
        
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
        layerView.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        
        let tagsView = UIView(frame: CGRect(x: 0, y: 0, width: 49, height: 18) * .scale)
        tagsView.isHidden = true
        imgV.addSubview(tagsView)
        let sLayer = CAShapeLayer()
        sLayer.fillColor = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
        sLayer.path = UIBezierPath(roundedRect: tagsView.bounds, byRoundingCorners: [.bottomRight], cornerRadii: CGSize(width: 4, height: 4) * .scale).cgPath
        tagsView.layer.addSublayer(sLayer)
        let tagLabel = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), alignment: .center, text: "限时免费")
        tagsView.addSubview(tagLabel)
        tagLabel.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: "可视化程序设计及应用")
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalToSuperview()
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), text: "1242人加入学习")
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(label1.snp.bottom).offset(.scale*6)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1), text: "共9节 | 免费")
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(-.scale*16)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.width.lessThanOrEqualTo(.scale*150)
        }
        
        modelPS.subscribe(onNext: { item in
            let vipIsFree = item.vipIsFree == "vipFree"
            let (p, _) = xsGetPrice(vipIsFree: item.vipIsFree, isFree: item.isFree, vipPrice: item.vipPrice, discountPrice: item.discountPrice, price: item.price)
            layerView.isHidden = !vipIsFree
            imgV.sd_setImage(with: URL(string: item.curriculumImgUrl))
            
            if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "vip" {
                layerView.isHidden = true
                tagsView.isHidden = true
            } else {
                if let infoModel = XS_Singleton.shared.infoModel, infoModel.userBO.userType == "user", (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) <= 0 {
                    layerView.isHidden = true
                    tagsView.isHidden = false
                } else if (Double(item.vipPrice) ?? 0) <= 0, (Double(item.discountPrice) ?? 0) > 0  {
                    layerView.isHidden = false
                    tagsView.isHidden = true
                } else {
                    layerView.isHidden = true
                    tagsView.isHidden = true
                } 
            }
            
            label1.text = item.curriculumName
            label2.text = "\(item.purchaseNum)人加入学习"
            label3.text = "共\(item.curriculumNum)节 | " + (p.count > 0 ? "￥\(p)" : "免费")
        }).disposed(by: disposeBag)
        
        return view
    }
}
